<?php
/**
 * Author:  tangxiaowen
 * Date:    2018/11/23 0023 14:53
 * Mail:    846506584@qq.com
 * describe 云片短信发送
 */
namespace Api\Controller\Message;

class MessageController
{
    private static $MsgConfig;
	private static $MsgConfigCode;

    /**
	 * 获取短片短信配置信息
	 * @param string $type 短信类型
	 */
    public function __construct($type = 'code')
    {
        //初始化短片短信配置
        $this->yunpianInit($type);
    }

    /**
     * 发送单条短信
     * @param mobile 接收短信的手机号
     * @param text string 发送短信模板
	 * @param string $apiKeyType 短信类型
     * @return bool
     */
    public function send_msg($mobile,$template){

        $MsgConfig = self::$MsgConfig;
        $tempData = array(
            'apikey' => isset($MsgConfig['apikey'])?$MsgConfig['apikey']:'',
            'mobile' => $mobile,
            'text'   => $template,
        );
        $url = isset($MsgConfig['msg_send'])?$MsgConfig['msg_send']:'';
        $result = $this->msg_send_curl($url,$tempData);
		
        return $result;
    }

    /**
     * 初始化云片短信配置
     */
    private function yunpianInit($type){

		$where['ParaName'] = ($type != 'code')?'yunpiancode':'yunpian';
        //从缓存读取云片apikey若不存在则查询数据库 由于没有在编辑添加时做缓存 处于同步考虑这里缓存较短10秒
        $apikey = S($type);
        if($apikey === false){
            $apikey = M('sys_inteparameter')->where($where)->getField('ParaValue');
            S($type,$apikey,10);
            $apikey = S($type);
        }

        self::$MsgConfig = [
            'apikey'   => $apikey,
            'msg_send' => C('msg_send'),
        ];
    }

    /**
     * curl_init_fun 请求
     * @param string $url 请求的url地址
     * @param string $param 请求的参数
     * @param bool $isPost 请求方式
     * @return bool
     */
    private function msg_send_curl($url = null, $param = null)
    {
        if ($url === null) return false;
        $headers = array(
            'Accept:application/json;charset=utf-8;',
            'Content-Type:application/x-www-form-urlencoded;charset=utf-8;',
        );
        $culObj = curl_init();
        //设置请求的curl
        curl_setopt($culObj, CURLOPT_URL, $url);
        //不输出文件头(直接获取内容部分)
        curl_setopt($culObj, CURLOPT_HEADER, false);
        //设置curl请求方式
        curl_setopt($culObj, CURLOPT_POST, true);
        //设置请求的参数
        curl_setopt($culObj, CURLOPT_POSTFIELDS, http_build_query($param));
        //将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($culObj, CURLOPT_RETURNTRANSFER, true);
        //禁止 cURL 验证对等证书（peer's certificate）
        curl_setopt($culObj, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($culObj, CURLOPT_HTTPHEADER, $headers);
        //允许Curl函数执行的最长秒数。这里设置为30秒
        curl_setopt($culObj, CURLOPT_TIMEOUT, 30);
        $result = curl_exec($culObj);
        curl_close($culObj);
        return $result;
    }

}